'
' Copyright (c) 2007-2008
' by Joe Brinkman
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
'
Imports System.Web.UI
Imports System.Collections.Generic
Imports System.Reflection

Imports DotNetNuke
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Services.Localization
Imports System.Management.Automation
Imports System.Management.Automation.Runspaces
Imports System.Collections.ObjectModel
Imports DotNetNuke.Entities.Modules.Actions

Namespace DotNetNukeCorp.Modules.Posh4DNN

    Partial Class ViewPosh4DNN
        Inherits Entities.Modules.PortalModuleBase
        Implements Entities.Modules.IActionable

#Region "Event Handlers"

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try
                If Not Page.IsCallback And Not Page.IsPostBack Then
                    If AJAX.IsInstalled Then
                        Dim mgr As ScriptManager = ScriptManager.GetCurrent(Me.Page)
                        Dim SRef As New ScriptReference()
                        SRef.Path = "~/DesktopModules/Posh4DNN/PoshScroll.js"
                        mgr.Scripts.Add(SRef)
                    End If
                End If
            Catch exc As Exception        'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

#End Region

#Region "Optional Interfaces"

        Public ReadOnly Property ModuleActions() As ModuleActionCollection Implements DotNetNuke.Entities.Modules.IActionable.ModuleActions
            Get
                Dim Actions As New ModuleActionCollection
                'Actions.Add(GetNextActionID, Localization.GetString(ModuleActionType.AddContent, LocalResourceFile), ModuleActionType.AddContent, "", "", EditUrl(), False, SecurityAccessLevel.Edit, True, False)
                Return Actions
            End Get
        End Property

#End Region

        Protected Function GetRunSpace() As Runspace
            If DataCache.GetCache("p4d_rs") Is Nothing Then
                Dim rs As Runspace = RunspaceFactory.CreateRunspace
                rs.Open()
                DataCache.SetCache("p4d_rs", rs)
            End If

            Return CType(DataCache.GetCache("p4d_rs"), Runspace)
        End Function

        Private Sub cmdInvoke_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdInvoke.Click
            'HACK: This should be replaced by properly implementing a host application which would properly handle updating the screen
            If txtCommand.Text.Trim = "cls" Or txtCommand.Text.Trim = "clear-host" Then
                txtConsole.Value = String.Empty
            Else
                Dim results As New Collection(Of PSObject)
                Try
                    Dim rs As Runspace = GetRunSpace()
                    rs.SessionStateProxy.SetVariable("HttpContext", HttpContext.Current)
                    rs.SessionStateProxy.SetVariable("PortalSettings", PortalSettings)
                    'HACK: This should be replaced by properly implementing a host application which would properly handle updating the screen
                    Dim StringOutCommand As String = String.Format("{0} | out-string", txtCommand.Text)
                    Dim cmd As Pipeline = rs.CreatePipeline(StringOutCommand, True)
                    results = cmd.Invoke()
                Catch ex As Exception
                    'TODO: We should log an error here.  
                    'Errors usually occur because we tried to use a cmdlet that outputs to the host 
                    ' or we didn't let a previous command in the pipeline finish processing.
                    Dim cmd As Pipeline = GetRunSpace().CreatePipeline("$error[0] | out-string", False)
                    results = cmd.Invoke()
                End Try
                Dim sb As New StringBuilder()

                sb.AppendLine("PS> " & txtCommand.Text)

                If results IsNot Nothing Then
                    For Each ps As PSObject In results
                        sb.AppendLine(ps.ToString)
                    Next
                End If

                txtConsole.Value &= sb.ToString
            End If

            ' Clear the commandline and reset the focus
            txtCommand.Text = String.Empty
            If AJAX.IsInstalled Then ScriptManager.GetCurrent(Me.Page).SetFocus(txtCommand)

        End Sub

    End Class

End Namespace
